import { ref, reactive } from 'vue';
import { getPageSize, isNull } from '/@/utils';
import { SqlSugarPagedList } from '/@/api/BaseDto';
import { BaseKeywordPageInput } from '/@/api/BaseDto';

// 分页查询, fnPage: page接口, fnOnfinish: 查询完成后回调
export const usePageQuery = <TO, TI extends object = BaseKeywordPageInput>(fnPage: Function, fnOnFinish: Function = () => {}) => {
	// 查询入参
	const searchParam = reactive<TI>({
		page: 1,
		pageSize: getPageSize(),
	} as TI);
	// 表格数据
	const tableData = ref<TO[]>([]);
	const total = ref(0);
	// 加载状态
	const loading = ref(false);
	// 查询
	const search = async () => {
		try {
			loading.value = true;
			const { total: itemsTotal, items }: SqlSugarPagedList<TO> = await fnPage({
				...searchParam,
			});
			total.value = itemsTotal;
			if (!isNull(items)) {
				// @ts-ignore
				tableData.value = items;
			} else {
				tableData.value = [];
			}
		} catch (err) {
			console.log('获取申请单数据失败', err);
		} finally {
			loading.value = false;
			fnOnFinish();
		}
	};

	return {
		searchParam,
		total,
		tableData,
		loading,
		search,
	};
};
